<?php

/*
 * zhuojianhe
 * OrderController
 */
namespace SDXApi\Controller;

use Think\Controller;
use Think\Model;
Vendor('alipush.aliyun-php-sdk-core.Config');
use \Push\Request\V20150827 as Push;

class OrderSendmsgController extends Controller {

	public function repair(){
		M("comment")->alias("c")->join("left join sdx_user_bonus as sub on c.bonus_sn=sub.bonus_sn")->where(array('sub.get_time'=>0))->field("swp.wechat_barcode_img,swp.name,sau.user_name as phone")->select();
	}
	
	/*
     * 查询推送状态
     */
    public function check_app_push(){
        $push_list=M("message_log")->field("alimsg_id,send_time")->where(array('app_state'=>2,'alimsg_id'=>array('gt',0)))->limit(50)->select();
        foreach($push_list as $item){
            
            $response=$this->QueryPushStat($item['alimsg_id']);
            
            $result=$response->PushStats->PushStat[0]->ReceivedCount;
            
            
            if(!empty($result) && $result>0){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('app_state'=>1));
            }else if(!empty($result) && $result==0 || $item['send_time']<date("Y-m-d H:i:s")){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('app_state'=>0));
            }
        }
        
        $push_list=M("message_log")->field("alimsg_id,send_time,templates_id")->where(array('android_state'=>2,'alimsg_id'=>array('gt',0)))->limit(50)->select();
        foreach($push_list as $item){
        
            $response=$this->QueryPushStat($item['alimsg_id']);
            
            $result=$response->PushStats->PushStat[0]->ReceivedCount;
            $OpenedCount=$response->PushStats->PushStat[0]->OpenedCount;
        
            if(!empty($OpenedCount) && $OpenedCount>0){
                M("mail_templates")->where(array('template_id'=>$item['templates_id']))->setInc("android_opened");
            }
        
            if(!empty($result) && $result>0){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('android_state'=>1));
                M("mail_templates")->where(array('template_id'=>$item['templates_id']))->setInc("android_received");
            }else if(!empty($result) && $result==0 || $item['send_time']<date("Y-m-d H:i:s")){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('android_state'=>0));
            }
        }
        
        $push_list=M("message_log")->field("alimsg_id,send_time,templates_id")->where(array('ios_state'=>2,'alimsg_id'=>array('gt',0)))->limit(50)->select();
        foreach($push_list as $item){
        
            $response=$this->QueryPushStat($item['alimsg_id']);
            
            $result=$response->PushStats->PushStat[0]->ReceivedCount;
            $OpenedCount=$response->PushStats->PushStat[0]->OpenedCount;
        
            if(!empty($OpenedCount) && $OpenedCount>0){
                M("mail_templates")->where(array('template_id'=>$item['templates_id']))->setInc("ios_opened");
            }
        
            if(!empty($result) && $result>0){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('ios_state'=>1));
                M("mail_templates")->where(array('template_id'=>$item['templates_id']))->setInc("ios_received");
            }else if(!empty($result) && $result==0 || $item['send_time']<date("Y-m-d H:i:s")){
                M("message_log")->where(array('alimsg_id'=>$item['alimsg_id']))->save(array('ios_state'=>0));
            }
        }
        
        echo 'Success';
    }
    

    private function QueryPushStat($msg_id){
        // 设置你自己的AccessKeyId/AccessSecret/AppKey
        $accessKeyId = C("ALIPUSH_ACCESSKEYID");
        $accessSecret = C("ALIPUSH_ACCESSSECRET");
        $appKey = C("ALIPUSH_APPKEY");
        
   
    
        $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $accessKeyId, $accessSecret);
    
        $client = new DefaultAcsClient($iClientProfile);
        $request = new Push\QueryPushStatRequest();
    
        // 推送目标
        $request->setAppKey($appKey);
        $request->setMessageId($msg_id);
    
        $response = $client->getAcsResponse($request);
        print_r($response);
        echo '<br>';
        
        
        //$stats=$response->PushStats->PushStat[0]->ReceivedCount;
        return $response;
    }
    
	/**
	 * 确认收货后2小时发短信
	 */
	
	public function myorder_confirm_sendmsg(){
	    
	    $list=M("order_confirm_sendmsg")->alias("ocs")->join("left join sdx_order_info as soi on ocs.order_id=soi.order_id")->where(array('ocs.is_send'=>0,'soi.confirm_time'=>array('between',(strtotime("-7 days")- date('Z')-7200).','.(strtotime("now")- date('Z')-7200))))->Field("ocs.id,ocs.order_sn,soi.order_id,ocs.consignee,ocs.mobile_phone,ocs.uid,ocs.send_time")->select();
	    foreach($list as $key=>$value){
	        $code=md5($value['id'].'sdx@9999');
	        switch($_SERVER['SERVER_NAME']){
	            case 'api.xian3.com':
	                $thisurl='xian3.com';
	                break;
	            case 'api.test.shidexian.com':
	                $thisurl='test.shidexian.com';
	                break;
	            case 'api.shidexian.com':
	                $thisurl='w.shidexian.com';
	                break;
	            default:
	                $thisurl='w.shidexian.com';
	                break;
	        }
	        $url='https://'.$thisurl.'/index_c.php?index&sid='.$value['id'].'&code='.$code.'&lll=#!/reted?ordId='.$value['order_sn'];
	        $url=$this->xlUrlAPI($url);
	        
	        $comoridc=M("comment")->where(array('order_sn'=>$value['order_sn']))->count();
	        if($comoridc){
	            M("order_confirm_sendmsg")->where(array('id'=>$value['id']))->setField('is_send',1);
	        }
	        if($url && !$comoridc){
	            if(empty($value['consignee'])){
	                $value['consignee']='食得鲜用户';
	            }
	            $wechat_param=array();
	            $wechat_param['url']='https://'.$thisurl.'/?index&sid='.$value['id'].'&code='.$code.'&lll=#!/reted?ordId='.$value['order_sn']."&utm_source=GZHcomment_201702";
	            $wechat_param['keyword1']=$value['order_sn'];
	            $wechat_param['keyword2']=date("Y-m-d");
	            $msg_opt=M("mail_templates")->where(array('template_code'=>'comment_201702'))->getField("msg_opt");
	            
	            $goods_name=M("order_goods")->where(array('order_id'=>$value['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$value['order_id'].')')))->limit(1)->getField("goods_name");
	            $goods_number=M("order_goods")->where(array('order_id'=>$value['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$value['order_id'].')')))->count();
	            
    	        $send_result = A("Smsapi")->send_message_api('comment_201702',$value['mobile_phone'],$value['consignee'],0,$value['order_sn'],0,$value['uid'],array('url'=>urlencode($url),'time'=>date("Y-m-d",$value['send_time']+28800),'msg_opt'=>$msg_opt,'goods_name'=>$goods_name,'goods_number'=>$goods_number),'',$wechat_param);
    	        M("order_confirm_sendmsg")->where(array('id'=>$value['id']))->setField('is_send',1);
    	        echo $value['order_sn'].' has been sent<br>';
	        }
	    }
	     
	}
	
    //没有评价，7天内默认好评
	public function default_comment(){
	    
	    $list=M("order_confirm_sendmsg s")->join("left join sdx_comment c on s.order_sn=c.order_sn left join sdx_order_info as soi on s.order_id=soi.order_id")->where(array('s.is_send'=>1,'soi.confirm_time'=>array('between',(strtotime("-30 days")- date('Z')+(2*60*60)).','.(strtotime("-7 days")- date('Z')+(2*60*60))),'c.comment_id'=>array("EXP",'is NULL')))->field("s.order_id,soi.shipping_time,soi.order_sn")->select();
	    foreach($list as $item){
	        
	        $orderinfo = M("order_info")->where(array("order_id"=>$item['order_id']))->find();
	        
	        if(empty($orderinfo)){
	            continue;
	        }
	        $order_goods = M("order_goods")->where(array("order_id"=>$item['order_id']))->select();
	        
	        $goods_le_arr=array();
	        foreach($order_goods as $goods_item){
	            $goods_le_arr[]=$goods_item['goods_id'].",5";
	        }
	        
	        
	        
	        $goods_level=implode(';',$goods_le_arr);
	        
	        $delivery_time=date("H:i",$item['shipping_time']);
	        $openid='';
	        
	        $add_re=$this->add_comment($orderinfo, 5, "", $goods_level, $delivery_time, $openid);
	        if($add_re!=false){
	            echo $item['order_sn'].'<br>';
	        }
	    }
	    
	    echo 'Success';
	}
	
	private function add_comment($orderinfo,$level,$content,$goods_level,$delivery_time,$openid){
	    if(!empty($openid)){
	        $user_name = M("wechat_user")->where(array("openid"=>$openid))->getField("nickname");
	    }
	    if(empty($user_name)){
	        $user_name=substr_replace($orderinfo['mobile'],'****',3,4);
	    }
	    $data = array();
	    $data['user_id'] = $orderinfo['user_id'];
	    $data['comment_status'] = 1;                        //状态，默认为不显示
	    $data['add_time'] = gmtime();
	    $data['comment_rank'] = $level;    //评价分数
	    $data['content'] = addslashes($content);   //评价内容
	    $data['user_name'] = $user_name;   //评价人名称
	    $data['distribution_time'] = $orderinfo['shipping_time']!=0?strtotime(date("Y-m-d",localtotime($orderinfo['shipping_time'])).' '.$delivery_time):0;   //配送时间
	    $data['sender_name'] = M("warehouse_personnel")->where(array("uid"=>$orderinfo['wp_userid']))->getField("name");   //配送时间
	    $data['order_sn'] = $orderinfo['order_sn'];   //关联订单号
	    $data['delivery_time'] = $delivery_time;   //送达时间
		$data['is_auto'] = 1;   //送达时间
	
	    $add_re = M('comment')->add($data);
	    if($add_re!=false){
	        $goods_list=array();
	        foreach(explode(';',$goods_level) as $goods_item){
	            $thisGoods=explode(',',$goods_item);
	            $goods_list[$thisGoods[0]]=$thisGoods[1];
	        }
	        array_unique($goods_list);
	        foreach($goods_list as $key=>$value){
	            $goods = M("goods")->where(array("goods_id"=>$key))->find();
	            $data = array();
	            $data['comment_id'] = $add_re;
	            $data['goods_id'] = $key;
	            $data['goods_sn'] = $goods['goods_sn'];
	            $data['comment_rank'] = $value;    //评价分数
	            $data['goods_name'] = $goods['goods_name'];
	            M('comment_goods')->add($data);
	        }
	
	
	    }
	
	    return $add_re;
	
	}
	
	
    public function xlUrlAPI($url){
	    
	    $wechat = M('wechat')->where('default_wx=1')->find();
	    $thisoptions['token']= $wechat['token'];
	    $thisoptions['appid']= $wechat['appid'];
	    $thisoptions['appsecret']= $wechat['appsecret'];
	    
	    $weObj =  new TPWechat($thisoptions);
	    $result=$weObj->getShortUrl($url);
	    
	    return $result;
	    
    }

	public function checkFreezeState(){
		$order_list = M("order_goods")->alias("og")->join(" left join sdx_order_info as oi on og.order_id=oi.order_id")->where(array("oi.referer"=>'891',"oi.order_status"=>1,"oi.pay_status"=>2,'oi.pay_id'=>array('in','1,2'),"oi.add_time"=>array("between",(strtotime("2017-09-08")- date('Z')).','.(strtotime("2017-09-09")- date('Z')))))->order("order_id desc")->select();
		foreach($order_list as $li){
			$record4 = M("goods_freeze_record")->where(array("goods_id"=>$li['goods_id'],"source_no"=>$li['order_sn'],"record_type"=>4))->find();
			if(!$record4){
				echo $li['order_sn'].'--'.$li['goods_id']."--4\n";
			}
		}
		echo count($order_list);

	}

	//支付主动查询状态
	public function check_order_pay_status(){
		$order_list = M("order_info")->where(array("order_status"=>0,"pay_status"=>1,'shipping_status'=>0,'shipping_status'=>0,"add_time"=>array("between",(gmtime()-181).','.(gmtime()-3600))))->select();
		foreach($order_list as $li){
			$order_info = M('order_info')->where(array("order_id"=>$li['order_id']))->find();
			if($order_info['order_status']==0 && $order_info['pay_status']==1 && $order_info['shipping_status']==0){
				$update = D('Payment')->order_paid($order_info['order_sn'],PS_PAYED,'',PAY_ORDER,$_POST);
			}
		}
	}


	public function start_service_for_negative_to_sell(){
		$negative_to_sell_wid=array(
			array("time"=>'07:00:00',"start_service"=>"09:00-11:00"),
			array("time"=>'09:30:00',"start_service"=>"11:00-21:30"),
		);
		foreach($negative_to_sell_wid as $key=>$nWid){
			if($nWid['time']<date("H:i")){
				$startTime=explode("-",$nWid['start_service']);

				$negative_to_sell_order=M("order_info")->where(array("buckle_inventory"=>0,"is_negative_to_sell"=>1,"order_status"=>1,"pay_status"=>2,'shipping_status'=>0,"best_time"=>array("between",strtotime($startTime[0]).','.strtotime($startTime[1]))))->select();

				foreach($negative_to_sell_order as $order){
					$order_goods=M("order_goods")->where(array("order_id"=>$order['order_id']))->select();

					//处理全额退款
					$param=array();
					$param['order_id']=$order['order_id'];
					$param['refund_amount']=$order['money_paid']+$order['surplus'];
					$param['refund_type']='退货退款';
					$param['refund_note']='商品缺货退款';
					$param['admin_id']=1;
					$param['refund_channel']=0;
					$param['user_name']='负卖脚本';
					$i=0;
					foreach($order_goods as $goods){
						$param['goods_list['.$i.'][goods_discount]']=$goods['goods_discount'];
						$param['goods_list['.$i.'][discount_price]']=$goods['discount_price'];
						$param['goods_list['.$i.'][act_id]']=$goods['act_id'];
						$param['goods_list['.$i.'][giving]']=$goods['giving'];
						$param['goods_list['.$i.'][rec_id]']=$goods['rec_id'];
						$param['goods_list['.$i.'][goods_id]']=$goods['goods_id'];
						$param['goods_list['.$i.'][goods_name]']=$goods['goods_name'];
						$param['goods_list['.$i.'][goods_sn]']=$goods['goods_sn'];
						$param['goods_list['.$i.'][market_price]']=$goods['market_price'];
						$param['goods_list['.$i.'][goods_number]']=$goods['goods_number'];
						$param['goods_list['.$i.'][goods_price]']=$goods['goods_price'];
						$param['goods_list['.$i.'][goods_attr]']=$goods['goods_attr'];
						$param['goods_list['.$i.'][is_real]']=$goods['is_real'];
						$param['goods_list['.$i.'][parent_id]']=$goods['parent_id'];
						$param['goods_list['.$i.'][is_gift]']=$goods['is_gift'];
						$param['goods_list['.$i.'][subtotal]']=$goods['goods_price'];
						$param['goods_list['.$i.'][extension_code]']=$goods['extension_code'];
						$param['goods_list['.$i.'][is_presell]']=$goods['is_presell'];
						$param['goods_list['.$i.'][buckle_inventory]']=$goods['extension_code'];
						$param['goods_list['.$i.'][goods_weight]']=$goods['goods_weight'];
						$param['goods_list['.$i.'][spec_value]']='';
						$param['goods_list['.$i.'][spec_unit]']='';
						$param['goods_list['.$i.'][specifications]']='';
						$param['goods_list['.$i.'][goods_num]']=$goods['goods_number'];
						$param['goods_list['.$i.'][original_number]']=$goods['goods_number'];
						$param['goods_list['.$i.'][refund_number]']=0;
						$param['goods_list['.$i.'][surplus_number]']=$goods['goods_number'];
						$param['goods_list['.$i.'][cnt2]']=0;
						$param['goods_list['.$i.'][cnt]']=$goods['goods_number'];
						$i++;
					}
					$param['goods_nums']=$i;
					$url=C("SDX_SEND_DOMIANURL").'index.php?m=admin&c=store&a=refund&api=skip';
					$this->http_post($url,$param);


					$saveData=array(
						"is_negative_to_sell_stockout"=>1,
						"is_negative_to_sell_stockout_time"=>gmtime()
					);
					M("order_info")->where(array("order_id"=>$order['order_id']))->save($saveData);
				}


			}
		}
		echo 'Success';
	}


	/**
	 * POST 请求
	 * @param string $url
	 * @param array $param
	 * @param boolean $post_file 是否文件上传
	 * @return string content
	 */
	function http_post($url,$param,$post_file=false){
		$oCurl = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
		}
		if (is_string($param) || $post_file) {
			$strPOST = $param;
		} else {
			$aPOST = array();
			foreach($param as $key=>$val){
				$aPOST[] = $key."=".urlencode($val);
			}
			$strPOST =  join("&", $aPOST);
		}
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_POST,true);
		curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
		$sContent = curl_exec($oCurl);
		$aStatus = curl_getinfo($oCurl);
		curl_close($oCurl);
		if(intval($aStatus["http_code"])==200){
			return $sContent;
		}else{
			return false;
		}
	}

	//门店负卖订单
	public function order_for_negative_to_sell(){
		$wid=$_REQUEST['wid'];
		$startTime=array("00:00","24:00");

		$negative_to_sell_order=M("order_info")->where(array("is_presell"=>1,'wid'=>$wid,"best_time"=>array("between",strtotime($startTime[0]).','.strtotime($startTime[1]))))->select();
		echo '负卖订单数：'.count($negative_to_sell_order);
		echo '<br>';
		foreach($negative_to_sell_order as $order){
			echo $order['order_sn'];
			echo '<br>';
		}

	}

	
}